package com.galen.manual.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.galen.manual.dto.ProductCreateDTO;
import com.galen.manual.dto.ProductQueryDTO;
import com.galen.manual.entity.Product;
import com.galen.manual.mapper.ProductMapper;
import com.galen.manual.service.MinioService;
import com.galen.manual.service.ProductService;
import com.galen.manual.vo.ProductDetailVO;
import com.galen.manual.vo.ProductListVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {

    private final ProductMapper productMapper;
    private final MinioService minioService;

    @Override
    public List<ProductListVO> getProductList(ProductQueryDTO queryDTO) {
        log.info("获取手工品列表，关键词: {}, 页码: {}, 每页大小: {}",
                queryDTO.getKeyword(), queryDTO.getPageNum(), queryDTO.getPageSize());

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();

        // 只查询上架状态的商品
        queryWrapper.eq("status", 1);

        // 关键词搜索
        if (queryDTO.getKeyword() != null && !queryDTO.getKeyword().trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like("name", queryDTO.getKeyword())
                .or()
                .like("description", queryDTO.getKeyword())
            );
        }

        // 标签搜索（注意：这里假设tags字段存储在某个地方，如果数据库中没有tags字段，可以先注释掉）
        // if (queryDTO.getTags() != null && !queryDTO.getTags().trim().isEmpty()) {
        //     queryWrapper.like("tags", queryDTO.getTags());
        // }

        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");

        // 分页查询
        int offset = (queryDTO.getPageNum() - 1) * queryDTO.getPageSize();
        queryWrapper.last("LIMIT " + offset + ", " + queryDTO.getPageSize());

        List<Product> products = productMapper.selectList(queryWrapper);

        return products.stream().map(this::convertToListVO).collect(java.util.stream.Collectors.toList());
    }

    @Override
    public ProductDetailVO getProductDetail(Long id) {
        log.info("获取手工品详情，ID: {}", id);

        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new RuntimeException("手工品不存在");
        }

        // 增加浏览次数
        product.setViewCount(product.getViewCount() == null ? 1 : product.getViewCount() + 1);
        productMapper.updateById(product);

        return convertToDetailVO(product);
    }

    @Override
    public void createProduct(ProductCreateDTO createDTO) {
        log.info("创建手工品: {}", createDTO.getName());

        Product product = new Product();
        product.setName(createDTO.getName());
        product.setDescription(createDTO.getDescription());
        product.setUnitPrice(createDTO.getPrice());

        // 处理图片URL列表
        if (createDTO.getImages() != null && !createDTO.getImages().isEmpty()) {
            String imageUrls = String.join(",", createDTO.getImages());
            product.setImageUrls(imageUrls);
        }

        // 设置默认值
        product.setStatus(1); // 默认上架
        product.setViewCount(0);
        product.setOrderCount(0);
        product.setCompletedCount(0);
        product.setStockQuantity(999); // 默认库存
        product.setWarningStock(10); // 默认预警库存
        product.setDifficultyLevel(1); // 默认简单

        productMapper.insert(product);
        log.info("手工品创建成功，ID: {}", product.getId());
    }

    @Override
    public String uploadImage(MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }

        try {
            log.info("开始上传手工品图片到Minio，原始文件名: {}", file.getOriginalFilename());

            // 生成唯一的对象名称
            String objectName = minioService.generateUniqueFileName(file.getOriginalFilename(), "products");

            // 上传到Minio并记录到数据库
            String fileUrl = minioService.uploadFile(
                file, objectName, "products", null, "product", request);

            log.info("手工品图片上传成功到Minio，对象名称: {}, 访问URL: {}", objectName, fileUrl);
            return fileUrl;

        } catch (Exception e) {
            log.error("手工品图片上传到Minio失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    @Override
    public List<String> uploadImages(MultipartFile[] files, HttpServletRequest request) {
        List<String> imageUrls = new ArrayList<>();
        if (files == null || files.length == 0) {
            return imageUrls;
        }

        for (MultipartFile file : files) {
            try {
                String imageUrl = uploadImage(file, request);
                imageUrls.add(imageUrl);
            } catch (Exception e) {
                log.error("批量上传中单个文件失败: {}", file.getOriginalFilename(), e);
                // 可以选择继续处理其他文件，或者抛出异常
                throw new RuntimeException("文件上传失败: " + file.getOriginalFilename() + " - " + e.getMessage());
            }
        }

        return imageUrls;
    }

    @Override
    public void updateProduct(Long id, ProductCreateDTO updateDTO) {
        log.info("更新手工品: {} - {}", id, updateDTO.getName());

        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new RuntimeException("手工品不存在");
        }

        // 更新基本信息
        product.setName(updateDTO.getName());
        product.setDescription(updateDTO.getDescription());
        product.setUnitPrice(updateDTO.getPrice());

        // 更新图片URL列表
        if (updateDTO.getImages() != null && !updateDTO.getImages().isEmpty()) {
            String imageUrls = String.join(",", updateDTO.getImages());
            product.setImageUrls(imageUrls);
        }

        productMapper.updateById(product);
        log.info("手工品更新成功，ID: {}", id);
    }

    @Override
    public void onlineProduct(Long id) {
        log.info("上架手工品: {}", id);

        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new RuntimeException("手工品不存在");
        }

        product.setStatus(1); // 1: 上架
        productMapper.updateById(product);
        log.info("手工品上架成功，ID: {}", id);
    }

    @Override
    public void offlineProduct(Long id) {
        log.info("下架手工品: {}", id);

        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new RuntimeException("手工品不存在");
        }

        product.setStatus(0); // 0: 下架
        productMapper.updateById(product);
        log.info("手工品下架成功，ID: {}", id);
    }

    /**
     * 转换为ProductListVO
     */
    private ProductListVO convertToListVO(Product product) {
        ProductListVO vo = new ProductListVO();
        vo.setId(product.getId());
        vo.setName(product.getName());
        vo.setDescription(product.getDescription());
        vo.setPrice(product.getUnitPrice());
        vo.setStatus(product.getStatus());

        // 处理封面图片（取第一张图片）
        if (product.getImageUrls() != null && !product.getImageUrls().trim().isEmpty()) {
            String[] images = product.getImageUrls().split(",");
            if (images.length > 0) {
                vo.setCoverImage(images[0]);
            }
        }

        // 设置创建者名称（暂时设置为空，后续可以从用户表获取）
        vo.setCreatorName("匿名用户");

        return vo;
    }

    /**
     * 转换为ProductDetailVO
     */
    private ProductDetailVO convertToDetailVO(Product product) {
        ProductDetailVO vo = new ProductDetailVO();
        vo.setId(product.getId());
        vo.setName(product.getName());
        vo.setDescription(product.getDescription());
        vo.setPrice(product.getUnitPrice());
        vo.setStatus(product.getStatus());
        vo.setCreateTime(product.getCreateTime());
        vo.setUpdateTime(product.getUpdateTime());

        // 处理图片列表
        if (product.getImageUrls() != null && !product.getImageUrls().trim().isEmpty()) {
            String[] images = product.getImageUrls().split(",");
            vo.setImages(java.util.Arrays.asList(images));
        } else {
            vo.setImages(new ArrayList<>());
        }

        // 设置创建者信息（暂时设置为默认值）
        vo.setCreatorId(1L);
        vo.setCreatorName("匿名用户");

        return vo;
    }
}